<?php
/**
 * User:chendenan
 * Created On 2022/3/19 0019 21:34
 */
namespace app\common\model\mysql;
class Goods extends ModelBase {
    public function searchTitleAttr($query,$value){
        $query->where('title','like','%'.$value.'%');
    }
    public function searchCreateTimeAttr($query,$value){
        $query->whereBetweenTime('create_time',$value[0],$value[1]);
    }
    public function getLists($likeKeys,$data,$num=10){
        $order = ["order"=>"desc","id"=>"desc"];
        if(!empty($likeKeys)){
            //搜索器
            $res = $this->withSearch($likeKeys,$data);
        }else{
            $res = $this;
        }
        $list = $res->whereIn("status",[0,1])->order($order)->paginate($num);
        return $list;
    }
    public function getGoodsByCondition($where,$field=true,$limit=5){
        $order = [
            "order"=>"desc",
            "id" => "desc",
        ];
        $where["status"] = config("status.mysql.table_normal");
        $result = $this->where($where)->field($field)->order($order)->limit($limit)->select();
        return $result;
    }
    public function getImageAttr($value){
        return request()->domain().$value;
    }
    public function getCarouselImageAttr($value){
        if(!empty($value)){
            $value = explode(',',$value);
            $value = array_map(function ($v){
                return request()->domain().$v;
            },$value);
        }
        return $value;
    }
    public function getGoodsFindInSetCategoryId($categoryId,$field){
        $order = ["order"=>"desc","id"=>"desc"];
        $result = $this->where("status","=",config("status.mysql.table_normal"))
            ->whereFindInSet("category_path_id",$categoryId)
            ->field($field)
            ->order($order)
            ->limit(10)
            ->select();
        return $result;
    }
    public function gettNormalLists($data,$num=10,$field=true,$order=["order"=>"desc","id"=>"desc"]){
        //$order = ["order"=>"desc","id"=>"desc"];
        $res = $this;
        if(isset($data['category_path_id'])){
            $res = $this->whereFindInSet("category_path_id",$data["category_path_id"]);
        }
        if(isset($data['title'])){
            $res = $res->where("title","like","%".$data['title']."%");
        }
        $list = $res->where("status","=",config("status.success"))
            ->order($order)
            ->field($field)
            ->paginate($num);
        return $list;
    }

    /**
     * 更新库存
     * @param $id
     * @param $num
     * @return mixed
     */
    public function decStock($id,$num) {
        return $this->where("id","=",$id)
            ->dec("stock",$num)
            ->update();
    }
}